package com.uduemc.biso.node.web.service.byfeign.impl;

import java.io.IOException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.uduemc.biso.core.utils.RestResult;
import com.uduemc.biso.node.core.entities.HDomain;
import com.uduemc.biso.node.core.entities.HRobots;
import com.uduemc.biso.node.core.feign.HRobotsFeign;
import com.uduemc.biso.node.core.utils.RestResultUtil;
import com.uduemc.biso.node.web.component.RequestHolder;
import com.uduemc.biso.node.web.component.wordfilter.CommonFilter;
import com.uduemc.biso.node.web.exception.NotFound404Exception;
import com.uduemc.biso.node.web.service.byfeign.RobotsService;

@Service
public class RobotsServiceImpl implements RobotsService {

	@Autowired
	private HRobotsFeign hRobotsFeign;

	@Autowired
	private RequestHolder requestHolder;

	@Autowired
	private CommonFilter commonFilter;

	@Override
	public String robots() throws NotFound404Exception, JsonParseException, JsonMappingException, JsonProcessingException, IOException {
		RestResult restResult = hRobotsFeign.findOneNotOrCreate(requestHolder.getHostId());
		HRobots hRobots = RestResultUtil.data(restResult, HRobots.class);
		commonFilter.hRobots(hRobots);
		Short status = hRobots.getStatus();
		if (hRobots == null || (status != null && status.shortValue() == (short) 0)) {
			throw new NotFound404Exception("robots 关闭不显示！");
		}

		HDomain hDomain = requestHolder.getAccessHost().getHDomain();
		if (hDomain != null) {
			Short domainType = hDomain.getDomainType();
			if (domainType != null && domainType.shortValue() == (short) 0) {
				return "User-Agent:  *\r\n" + "Disallow:  /";
			} else {
				String robots = hRobots.getRobots();
				if (StringUtils.isEmpty(robots)) {
					return "";
				}
				return robots;
			}
		}

		return "User-Agent:  *\r\n" + "Disallow:  /";
	}

}
